<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import videos from '../data/videos'
import VideoCard from '@/components/VideoCard.vue'
import EmptyState from '@/components/EmptyState.vue'
import ContentHeader from '@/components/ContentHeader.vue'
import { getCurrentUser } from '@/utils/auth'

const route = useRoute()
const router = useRouter()
const authorName = ref('')
const authorVideos = ref([])
const loading = ref(true)
const isFollowing = ref(false)
const totalPlays = ref(0)
const totalDanmakus = ref(0)
const avgPlays = ref(0)
const followerCount = ref(0)
const followingCount = ref(0)

// 解码URL中的作者名
const decodedAuthor = computed(() => {
  try {
    return decodeURIComponent(route.params.name || '')
  } catch (e) {
    return ''
  }
})

// 计算作者统计信息
const calculateAuthorStats = () => {
  totalPlays.value = authorVideos.value.reduce((sum, video) => sum + (video.plays || 0), 0)
  totalDanmakus.value = authorVideos.value.reduce((sum, video) => sum + (video.danmaku || 0), 0)
  avgPlays.value = authorVideos.value.length > 0 
    ? Math.round(totalPlays.value / authorVideos.value.length) 
    : 0
}

// 获取作者的视频
const fetchAuthorVideos = () => {
  loading.value = true
  authorName.value = decodedAuthor.value
  
  // 过滤出该作者的所有视频
  authorVideos.value = videos.filter(video => 
    video.author && video.author.toLowerCase() === authorName.value.toLowerCase()
  )
  
  // 计算统计信息
  calculateAuthorStats()
  
  // 模拟关注状态
  isFollowing.value = Math.random() > 0.5
  
  // 模拟粉丝量和关注数
  followerCount.value = Math.floor(Math.random() * 50000) + 1000
  followingCount.value = Math.floor(Math.random() * 500) + 50
  
  loading.value = false
}

// 返回上一页
const goBack = () => {
  if (window.history.length > 1) router.back()
  else router.push('/')
}

// 关注/取消关注作者
const toggleFollow = () => {
  const user = getCurrentUser()
  if (!user) {
    router.push('/login')
    return
  }
  
  isFollowing.value = !isFollowing.value
  // 这里只是模拟功能，实际项目中应该调用API
}

// 格式化数字显示
const formatNumber = computed(() => {
  return (num) => {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + '万'
    }
    return num.toLocaleString()
  }
})

// 组件挂载时获取数据
onMounted(() => {
  fetchAuthorVideos()
})
</script>

<template>
  <section class="author-view">
    <ContentHeader 
      :title="authorName"
      :subtitle="`共 ${authorVideos.length} 个视频`"
      :show-back="true"
      @back-click="goBack"
    />
    
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <p>正在加载作者信息...</p>
    </div>
    
    <template v-else>
      <div v-if="authorVideos.length > 0" class="author-content">
        <!-- 作者信息卡片 -->
        <div class="author-card">
          <div class="author-avatar">
            <div class="avatar-placeholder">
              {{ authorName.substring(0, 2) }}
            </div>
          </div>
          
          <div class="author-info">
            <h2 class="author-title">{{ authorName }}</h2>
            <div class="author-metrics">
              <span class="metric-item">
                <strong>{{ formatNumber.value(followerCount) }}</strong> 粉丝
              </span>
              <span class="metric-separator">·</span>
              <span class="metric-item">
                <strong>{{ formatNumber.value(followingCount) }}</strong> 关注
              </span>
            </div>
            <p class="author-bio">
              专注于高质量视频创作，为观众带来精彩内容。
            </p>
          </div>
          
          <button 
            class="follow-btn" 
            :class="{ following: isFollowing }"
            @click="toggleFollow"
          >
            <span class="icon">{{ isFollowing ? '✓' : '+' }}</span>
            <span>{{ isFollowing ? '已关注' : '关注' }}</span>
          </button>
        </div>
        
        <!-- 作者统计信息 -->
        <div class="author-stats">
          <div class="stat-card">
            <div class="stat-value">{{ formatNumber.value(totalPlays) }}</div>
            <div class="stat-label">总播放</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ formatNumber.value(totalDanmakus) }}</div>
            <div class="stat-label">总弹幕</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ formatNumber.value(avgPlays) }}</div>
            <div class="stat-label">平均播放</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ authorVideos.length }}</div>
            <div class="stat-label">视频数</div>
          </div>
        </div>
        
        <!-- 视频列表标题 -->
        <div class="videos-header">
          <h3>视频列表</h3>
          <span class="videos-count">{{ authorVideos.length }} 个视频</span>
        </div>
        
        <!-- 视频网格 -->
        <div class="videos-grid">
          <VideoCard 
            v-for="(video, index) in authorVideos" 
            :key="video.id"
            :video="video"
            :delay="index * 100"
          />
        </div>
      </div>
      
      <div v-else class="empty-state">
        <EmptyState 
          icon="👤"
          title="未找到该作者的视频"
          subtitle="可能该作者尚未发布任何视频，或作者名有误"
          :show-button="true"
          button-text="返回首页"
          @button-click="() => router.push('/')"
        />
      </div>
    </template>
  </section>
</template>

<style scoped>
.author-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.author-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 作者信息卡片 */
.author-card {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 32px;
  background: var(--surface);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border);
  box-shadow: var(--shadow);
  position: relative;
  overflow: hidden;
}

.author-card::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 300px;
  height: 300px;
  background: linear-gradient(135deg, var(--accent-light) 0%, transparent 70%);
  border-radius: 50%;
  transform: translate(50%, -50%);
  opacity: 0.5;
}

.author-avatar {
  flex-shrink: 0;
}

.avatar-placeholder {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--accent), var(--accent-hover));
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 3rem;
  font-weight: bold;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.author-info {
  flex: 1;
  position: relative;
  z-index: 1;
}

.author-title {
  margin: 0 0 8px;
  font-size: 2rem;
  font-weight: 800;
  color: var(--fg);
}

.author-metrics {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 0.95rem;
  color: var(--muted);
}

.metric-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.metric-separator {
  color: var(--border);
}

.metric-item strong {
  color: var(--fg);
  font-weight: 600;
}

.author-bio {
  margin: 0;
  color: var(--muted);
  font-size: 1rem;
  line-height: 1.6;
  max-width: 600px;
}

.follow-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  border-radius: 999px;
  border: 2px solid var(--accent);
  background: var(--surface);
  color: var(--accent);
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  position: relative;
  z-index: 1;
}

.follow-btn:hover {
  background: var(--accent);
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(99, 102, 241, 0.2);
}

.follow-btn.following {
  background: var(--accent);
  color: white;
}

.follow-btn.following:hover {
  background: var(--surface);
  color: var(--accent);
}

.follow-btn .icon {
  font-weight: bold;
}

/* 统计信息卡片 */
.author-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-card {
  padding: 24px;
  background: var(--surface);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border);
  text-align: center;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, var(--accent), var(--accent-light));
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-lg);
  border-color: var(--accent);
}

.stat-value {
  font-size: 2rem;
  font-weight: 800;
  color: var(--accent);
  margin-bottom: 8px;
}

.stat-label {
  color: var(--muted);
  font-size: 0.9rem;
}

/* 视频列表标题 */
.videos-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

.videos-header h3 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--fg);
}

.videos-count {
  color: var(--muted);
  font-size: 0.9rem;
}

/* 视频网格 */
.videos-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-top: 16px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  text-align: center;
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid var(--border);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading p {
  color: var(--muted);
  font-size: 1.1rem;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .author-card {
    flex-direction: column;
    text-align: center;
    padding: 40px 24px;
  }
  
  .author-info {
    max-width: 100%;
  }
  
  .author-stats {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .author-view {
    padding: 16px;
  }
  
  .author-card {
    padding: 32px 20px;
    gap: 20px;
  }
  
  .avatar-placeholder {
    width: 100px;
    height: 100px;
    font-size: 2.5rem;
  }
  
  .author-title {
    font-size: 1.75rem;
  }
  
  .author-stats {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .stat-card {
    padding: 20px 16px;
  }
  
  .stat-value {
    font-size: 1.75rem;
  }
  
  .videos-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
  }
}

@media (max-width: 480px) {
  .author-card {
    padding: 24px 16px;
  }
  
  .avatar-placeholder {
    width: 80px;
    height: 80px;
    font-size: 2rem;
  }
  
  .author-title {
    font-size: 1.5rem;
  }
  
  .author-stats {
    grid-template-columns: 1fr;
  }
  
  .videos-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .videos-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
}
</style>